import numpy as np
import cv2

# gx = a * fx + b
def updateAlpha(img, contrast):
    alpha = contrast / 50.0
    img = np.clip((alpha * img), 0, 255)
    return img.astype(np.uint8)

def updateBeta(img, brightness):
    beta =(brightness - 50) * 2.5
    img = np.uint8(np.clip((img + beta), 0, 255))
    return img.astype(np.uint8)
  
def change(img):
    # 创建窗口
    cv2.namedWindow('img', cv2.WINDOW_AUTOSIZE)
    cv2.createTrackbar('contrast', 'img', 50, 100, lambda x: None)
    cv2.createTrackbar('brightness', 'img', 50, 100, lambda x: None)

    # 备份原图像
    img_backup = img.copy()

    while True:
        cv2.imshow('img', img)

        # 读取值
        contrast = cv2.getTrackbarPos('contrast', 'img')
        brightness = cv2.getTrackbarPos('brightness', 'img')

        # 使用备份的图像进行处理
        img_temp = img_backup.copy()
        img_temp = updateAlpha(img_temp, contrast)
        img_temp = updateBeta(img_temp, brightness)
        img = img_temp.copy()

        key = cv2.waitKey(10)
        if key & 0xFF == ord('q'):
            break
        elif key == ord('s'):
            cv2.imwrite('./img/newtb.png', img)
        if cv2.getWindowProperty('img', cv2.WND_PROP_VISIBLE) <= 0:
            break

    cv2.destroyAllWindows()  # 关闭窗口